#include "unp.h"

#define MAXLINE 4096

void str_cli(FILE* file, int fd);

int main(int argc, char **argv)
{
  int sockfd;
  socklen_t svrlen;
  struct sockaddr_in svraddr;

  if (argc < 2)
  {
    printf("usage: cli <host> <port>\n");
    exit(-1);
  }

  sockfd = socket(AF_INET,SOCK_STREAM,0);
  memset(&svraddr,0,sizeof(svraddr));
  svraddr.sin_family = AF_INET;
  svraddr.sin_port = htons(atoi(argv[2]));
  inet_pton(AF_INET,argv[1],&svraddr.sin_addr);

  int ret = connect(sockfd,(struct sockaddr*)(&svraddr),sizeof(svraddr));
  if (ret < 0)
  {
    printf("connect error:%s\n",strerror(errno));\
    exit(-1);
  }

  str_cli(stdin,sockfd);

  return 0;
}

void str_cli(FILE* file, int fd)
{
  pid_t pid;
  char send[MAXLINE], recv[MAXLINE];
  memset(send,0,sizeof(send));
  memset(recv,0,sizeof(recv));

  pid = fork();
  if (pid == 0)
  {
    while (read(fd,recv,MAXLINE) > 0)
    {
      fputs(recv,stdout);
    }

    kill(getppid(),SIGTERM);
    exit(-1);
  }

  while (fgets(send,MAXLINE,file) != NULL)
  {
    write(fd,send,MAXLINE);
  }

  shutdown(fd,SHUT_WR);
  pause();
  return;
}
